package com.yonder.controller;

import com.yonder.common.MessageConstant;
import com.yonder.common.RedisConstant;
import com.yonder.entity.Result;
import com.yonder.pojo.Setmeal;
import com.yonder.service.SetmealService;
import com.yonder.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.util.Set;
import java.util.UUID;

/**
 * @ClassName SetmealController
 * @Description TODO
 * @Author zxs
 * @Date 2021/3/21 9:40
 * Version 1.0
 *
 * 套餐控制层
 *
 *
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private JedisPool jedisPool;
    /*
    * 增加套餐
    * */
    @RequestMapping(value ="/add",method = RequestMethod.POST)
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds){

        try {
            setmealService.setMealAdd( setmeal, checkgroupIds);
            return  new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
    }

    /*
    * 上传图片
    * */
    @RequestMapping( value="/upload",method = RequestMethod.POST)
    public Result upload(MultipartFile imgFile){

        try {
            //返回客户端文件系统中的原始文件名
            String oldFilename = imgFile.getOriginalFilename(); //1.jpg
            //因为client(客户端)上传的名字可能会相同，
            // 所以需要通过UUID类中的randomUUID方法重新定义名字
            //随机产生文件名称
            String uuidString = UUID.randomUUID().toString();
            //拼接文件名称
            String fileName = uuidString+oldFilename.substring(oldFilename.indexOf("."));
            //把文件上传到redist
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            //调用七牛云存储
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            return new Result(false, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
    }
}
